package com.ari.actions;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ParameterAware;

import ari.com.event.handler.EventMapper;
import ari.com.http.request.parser.ParamNotFoundException;
import ari.com.http.request.parser.ParamUtils;
import ari.com.http.request.parser.RequestParserFactory;

import com.ari.eft.command.Command;
import com.ari.eft.command.CommandFactory;
import com.ari.eft.request.type.EFTRequest;
import com.ari.xml.XMLResultGenerator;

/**
 * @author amith.nambiar
 * 
 */

public class PreviewAction implements ParameterAware {
	static final Logger logger = Logger.getLogger(PreviewAction.class);
	Map<String, String[]> requestParameters = new HashMap<String, String[]>();
	private String xml;

	/**
	 * @return
	 * @throws Exception
	 */
	public String execute() {
		try {
			Thread.sleep(1000);
		} catch (final InterruptedException e1) {
			e1.printStackTrace();
		}
		try {
			ParamUtils.getParameter(EventMapper.EFT_EVENT_TYPE,
					requestParameters);
		} catch (final ParamNotFoundException e) {
			e.printStackTrace();
		}

		/* Get the request type */
		EFTRequest request = null;
		try {
			request = RequestParserFactory.parseLoginRequest(requestParameters);
		} catch (final ParamNotFoundException e) {
			e.printStackTrace();
		}

		/* Get the corresponding event handler (Command) */
		final Command command = CommandFactory.getEventHandler(1 /*
																 * TODO Dummy
																 * now
																 */);
		command.setRequest(request);
		command.execute();

		if (command instanceof XMLResultGenerator) {
			xml = ((XMLResultGenerator) command).getXML();
		}
		return "preview";
	}

	public String getEscapedXML() {
		return StringEscapeUtils.escapeXml(xml);
	}

	@Override
	public String toString() {
		return null;
	}

	public void printMap(final Map<String, String[]> map) {
		final Iterator<String> iterator = map.keySet().iterator();
		System.out.println("Printing values:");
		while (iterator.hasNext()) {
			final String key = iterator.next().toString();
			final String[] value = map.get(key);
			System.out.println(key + " " + value[0]);
		}
	}

	@Override
	public void setParameters(final Map<String, String[]> parameters) {
		requestParameters = parameters;
		printMap(parameters);
	}
}
